#include "dialog.h"
#include "ui_dialog.h"
#include <QTextCodec>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    isStarted = false;
    udpSocket = new QUdpSocket(this);
    timer = new QTimer(this);

    connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::on_pushButton_clicked()
{
    if (!isStarted)
    {
        ui->pushButton->setText(tr("停止"));
        timer->start(1000);
        isStarted = true;
    }
    else
    {
        ui->pushButton->setText(tr("开始"));
        timer->stop();
        isStarted = false;
    }
}

void Dialog::onTimeout()
{
    QString msg = QTextCodec::codecForName("UTF8")->fromUnicode(ui->lineEdit->text());
    if (msg.isEmpty())
    {
        return;
    }

    QByteArray datagram = msg.toUtf8();
    qint64 length = udpSocket->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 5555);
    if (length != msg.size())
    {
        ;
    }
}
